<template>
  <!-- hidden PageHeaderWrapper title demo -->
  <page-header-wrapper :title="false">
    <a-card title="销售清单" style="margin-top: 24px">
      <div class="table-operator">
        <!-- <a-button type="primary" @click="handleChange()">修改保价详情</a-button> -->
        <a-button @click="handleAddGoodsEdit()">添加商品</a-button>
      </div>

      <a-table
        ref="table"
        size="default"
        rowKey="key"
        :columns="columns"
        :loading="searchLoading"
        :data-source="loadData"
        :pagination="pagination"
        @change="handleTableChange"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="action" slot-scope="text, record">
          <template>
            <a-tag color="#428BCA" @click="handleGoodsEdit(record)">编辑</a-tag>
            <a-tag color="#D15B47" @click="handleDelete(record)">删除</a-tag>
          </template>
        </span>
      </a-table>
    </a-card>
    <a-card :body-style="{ padding: '24px 32px' }" :bordered="false">
      <a-form @submit="handleSubmit" :form="submitform">
        <a-form-item :wrapperCol="{ span: 24 }" style="text-align: center">
          <a-button htmlType="submit" type="primary" icon="check" :loading="formLoading">提交</a-button>
          <a-button
            type="success"
            style="margin: 0px 5px; background: #87b87f !important; color: #fff"
            @click="setBack()"
          >返回</a-button
          >
          <!-- <a-button style="margin-left: 8px">{{ $t('form.basic-form.form.save') }}</a-button> -->
        </a-form-item>
      </a-form>
    </a-card>
    <price-form
      ref="priceModal"
      :visible="priceVisible"
      :loading="priceLoading"
      :model="priceMdll"
      @cancel="handlePriceCancel"
      @ok="handlePriceOk"
    />
    <add-goods
      ref="addGoodsModal"
      :visible="addGoodsVisible"
      :loading="addGoodsLoading"
      :model="addGoodsMdl"
      @cancel="handleAddGoodsCancel"
      @ok="handleAddGoodsOk"
    />
  </page-header-wrapper>
</template>

<script>
import { appendReturnsWholesaleUsingPOST, getWhDetailListUsingPOST } from '@/api/api/pifayewu.ts'
import PriceForm from './PriceForm'
import AddGoods from './addGoods'
export default {
  name: 'WholesaleSellRecordDetailEdit',
  components: {
    PriceForm,
    AddGoods,
  },
  data() {
    return {
      priceMdll: null,
      addGoodsMdl: null,
      addGoodsVisible: false,
      addGoodsLoading: false,
      priceLoading: false,
      submitform: this.$form.createForm(this),
      columns: [
        {
          title: '商品名',
          dataIndex: 'goodName',
        },
        {
          title: '串码1',
          dataIndex: 'phoneCode1',
        },
        {
          title: '串码2',
          dataIndex: 'phoneCode2',
        },
        {
          title: '单价(元)',
          dataIndex: 'price',
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '180px',
          scopedSlots: { customRender: 'action' },
        },
      ],
      priceVisible: false,
      pagination: {},
      formLoading:false,
      // 加载数据方法 必须为 Promise 对象
      loadData: [],
      searchLoading: false,
      optionParam: {
        pageNo: 1,
        pageSize: 999,
        queryCondition: '',
        status: 1,
      },
      queryParam: {
        pageNo: 1,
        pageSize: 10,
        queryCondition: '',
        status: '',
      },
    }
  },
  mounted() {
    this.handleSearch(this.queryParam)
  },
  methods: {
    setBack() {
      const that = this
      that.$confirm({
        title: '返回',
        content: '你确定放弃修改，返回订单吗？',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          that.$router.back()
        },
      })
    },
    handleSearch(params) {
      this.searchLoading = true
      getWhDetailListUsingPOST({ ...params, orderId: this.$route.params.id })
        .then((res) => {
          this.searchLoading = false
          this.loadData = res.data.list
          this.queryParam.pageNo = this.pagination.current
          this.pagination = { ...this.pagination, total: Number(res.data.total) }
        })
        .catch((error) => {
          this.searchLoading = false
          this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
    },
    handleTableChange(pagination, filters, sorter) {
      const pager = { ...this.pagination }
      pager.current = pagination.current
 pager.pageSize = pagination.pageSize
      this.pagination = pager
      this.handleSearch({
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...filters,
        pageNo: pagination.current,
        pageSize: pagination.pageSize,
        queryCondition: this.queryParam.queryCondition,
        status: this.queryParam.status,
        date: this.queryParam.date,
      })
    },
    handleDelete(record) {
      const that = this
      that.$confirm({
        title: '删除',
        content: '你确定要删除这个商品吗？',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          that.loadData.splice(
            that.loadData.findIndex((item) => item.id === record.id),
            1
          )
        },
      })
    },
    handleAddGoodsEdit() {
      this.addGoodsVisible = true
    },
    handleGoodsEdit(record) {
      this.priceMdll = record
      this.priceVisible = true
    },
    handlePriceOk() {
      const form = this.$refs.priceModal.form
      this.priceLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          // 修改 e.g.
          const index = this.loadData.map((i) =>i.id).indexOf(values.id)
          this.loadData[index].price = values.price
          this.priceLoading = false
          this.priceVisible = false
        } else {
          this.priceLoading = false
          this.priceVisible = false
        }
      })
    },
    handleAddGoodsOk() {
      const form = this.$refs.addGoodsModal.form
      this.addGoodsLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          // 修改 e.g.
          this.loadData.push(values)
          this.addGoodsLoading = false
          this.addGoodsVisible = false
        } else {
          this.addGoodsLoading = false
          this.addGoodsVisible = false
        }
      })
    },
    handlePriceCancel() {
      this.priceVisible = false
      const form = this.$refs.priceModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleAddGoodsCancel() {
      this.addGoodsVisible = false
      const form = this.$refs.addGoodsModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleSubmit(e) {
      e.preventDefault()
      this.formLoading = true
      appendReturnsWholesaleUsingPOST({ orderId: this.$route.params.id }, [...this.loadData])
        .then(() => {
          this.formLoading = false
          this.$message.success('操作成功')
          if (this.loadData.length == 0) {
            this.$router.push({ path: `/wholesale/backRecord/index` })
          } else {
            this.$router.back()
          }
          this.submitform.resetFields()
        })
        .catch((error) => {
          this.formLoading = false
          this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
    },
  },
}
</script>
